<template>
  <div>
    <div class="main_content">
      <el-form id="s_form" :model="searchForm" :inline="true" ref="searchForm">
        <el-form-item label="岗位：" prop="post">
          <el-select v-model="searchForm.post" clearable>
            <el-option
              v-for="item in allPost"
              :key="item.value"
              :label="item.post"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="searchText">
          <el-input
            style="width:200px;margin:0 7px"
            clearable
            v-model="searchForm.searchText"
            placeholder="请输入账号/姓名/性别"
            @keydown.enter.native="doSearch()"
          ></el-input>
          <el-button type="primary" @click="doSearch()" class="added">
            <i class="el-icon-search"></i>
            搜索
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="showBack" @click="resetForm">
            <i class="el-icon-back"></i>
            返回
          </el-button>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="toAdd()">
        <i class="el-icon-circle-plus-outline"></i>
        新增
      </el-button>
      <el-upload
        class="uploadfile"
        action
        :http-request="uploadFileMethod"
        :show-file-list="false"
        multiple
        style="display:inline;margin-left:10px;"
      >
        <el-button type="primary">
          <i class="el-icon-folder"></i>
          批量导入
        </el-button>
      </el-upload>
      <myTable
        style="margin-top:15px"
        auto='getAllList'
        :height='Height-210'
        min-width='130'
        :myColumn=tableProp
        ahide='index,checkbox,mySplitPage,tooltip,background'
        hide='checkbox'
        slots='操作,158,right'
        select='console'
        hook:created=' myTable.tableData = tableData '
      >
        <template slot-scope='button'>
          <el-button type="primary" size="mini" @click.stop="handleEdit(button.scope.$index, button.scope.row)">
            <i class="el-icon-edit"></i>
            编 辑
          </el-button>
          <el-button
            type="info"
            size="mini"
            @click="doJinYong(button.scope.$index, button.scope.row)"
            v-if="button.scope.row.userState == 1"
          >
            <i class="el-icon-warning-outline"></i>
            禁 用
          </el-button>
          <el-button
            type="success"
            size="mini"
            @click="doQiYong(button.scope.$index, button.scope.row)"
            v-if="button.scope.row.userState == 2"
          >
            <i class="el-icon-circle-check"></i>
            启 用
          </el-button>
          <!-- <el-button
           type="warning"
           size="mini"
           @click="editLimit(button.scope.$switch, button.scope.row)"
         >
         <i class="el-icon-edit"></i>
           编辑权限
         </el-button> -->
        </template>
      </myTable>
      <!-- <el-table
        :data="tableData"
        border
        style="width: 100%;margin-top:10px;"
        :header-cell-style="tableHeaderStyle"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="40" align="center"></el-table-column>
        <el-table-column prop="phoneNumber" label="账号" align="center"></el-table-column>
        <el-table-column prop="userName" label="姓名" align="center"></el-table-column>
        <el-table-column prop="post" label="岗位" align="center"></el-table-column>
        <el-table-column prop="gender" label="性别" align="center"></el-table-column>
        <el-table-column prop="userState" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.userState==1" style="color:green;">启用</span>
            <span v-else  style="color:red;">禁用</span>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.userState==1" style="color:green;">启用</span>
            <span v-else  style="color:red;">禁用</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDelete(scope.$switch, scope.row)">删除</el-button>
            <el-button type="primary" size="mini" @click="handleEdit(scope.$switch, scope.row)">编 辑</el-button>
            <el-button type="info" size="mini" @click="doJinYong()" v-if="button.scope.row.userState == 1">禁 用</el-button>
            <el-button type="success" size="mini" @click="doQiYong()" v-if="button.scope.row.userState == 2">启 用</el-button>
            <el-button type="warning" size="mini" @click="editLimit()">编辑权限</el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <!-- <div class="page">
        <el-pagination
          small
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="thePageSize"
          layout="total, prev, pager, next, jumper"
          :total="myTotal"
        ></el-pagination>
      </div> -->

    </div>
    <el-dialog v-dialogDrag ref="dialog_isDelete" title="提示" :visible.sync="isDelete" width="32%">
      <span>是否删除！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doDelete()">确 定</el-button>
      </span>
    </el-dialog>
    <!--新增 @close="closeDialog" -->
    <el-dialog v-dialogDrag :title="addOrEdit" :visible.sync="isAdd" width="40%" :close-on-click-modal=false
               :before-close='closeDialog'>
      <el-form :model="theAdd" :inline="true" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="账号" prop="phoneNumber">
          <el-input v-model="theAdd.phoneNumber" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="theAdd.userName" placeholder="请输入姓名" clearable></el-input>
        </el-form-item>
        <br>
        <el-form-item label="岗位" prop="post" placeholder="请选择岗位">
          <el-select v-model="theAdd.post" clearable>
            <el-option
              v-for="item in allPost"
              :key="item.value"
              :label="item.post"
              :value="item.value">
            </el-option>
            <!-- <option></option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="theAdd.department" clearable placeholder="请选择部门">
            <el-option
              v-for="item in allDepartment"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="theAdd.gender" clearable placeholder="请选择性别">
            <el-option
              v-for="item in allGender"
              :key="item.value"
              :label="item.gender"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select
            v-model="theAdd.major"
            multiple
            clearable
            placeholder="请选择专业"
            change='theAdd'
          >
            <el-option
              v-for="item in allMajor"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doAdd('ruleForm')">确 定</el-button>
        <!-- <el-button @click="isAdd = false">取 消</el-button> -->
        <el-button @click="addFalse('ruleForm')">取 消</el-button>
      </span>
    </el-dialog>
    <!--编辑-->
    <el-dialog v-dialogDrag ref="dialog_isAdd" title="编辑" :visible.sync="isEdit" width="40%"
               :close-on-click-modal=false>
      <el-form :model="theEdit" :inline="true" label-width="100px">
        <el-form-item label="账号" prop="phoneNumber">
          <el-input v-model="theEdit.phoneNumber" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="theEdit.userName" placeholder="请输入姓名" clearable></el-input>
        </el-form-item>
        <br>
        <el-form-item label="岗位" prop="post" placeholder="请选择岗位">
          <el-select v-model="theEdit.post" clearable>
            <el-option
              v-for="item in allPost"
              :key="item.value"
              :label="item.post"
              :value="item.value">
            </el-option>
            <!-- <option></option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="theEdit.department" clearable placeholder="请选择部门">
            <el-option
              v-for="item in allDepartment"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="theEdit.gender" clearable placeholder="请选择性别">
            <el-option
              v-for="item in allGender"
              :key="item.value"
              :label="item.gender"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="editSS">
          <el-select
            v-model="editSS"
            multiple
            clearable
            placeholder="请选择专业"
            @change="theEdit.editSS=false"
          >
            <el-option
              v-for="item in allMajor"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editFunction()">确 定</el-button>
         <el-button @click="isEdit = false">取 消</el-button>
      </span>
    </el-dialog>
    <!--编辑权限-->
    <!-- <el-dialog v-dialogDrag  :title="addOrEdit" :visible.sync="isEdit" width="60%">
      <el-form :model="theEdit" :inline="true" label-width="100px">
        <el-form-item label="姓名：" prop="userName">
          <el-input type="text" v-model="theEdit.userName"></el-input>
        </el-form-item>
        <el-form-item label="账号：" prop="phoneNumber">
          <el-input type="text" v-model="theEdit.phoneNumber"></el-input>
        </el-form-item><br>
        <el-form-item label="是否禁用：" prop="userState">
          <el-radio-group v-model="theEdit.userState">
            <el-radio label="启用" :value="1"></el-radio>
            <el-radio label="禁用" :value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否禁用：" prop="userState">
          <el-radio-group v-model="theEdit.userState">
            <el-radio label="启用" :value="1"></el-radio>
            <el-radio label="禁用" :value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="doEdit('ruleForm')">确 定</el-button>
         <el-button @click="isEdit = false">取 消</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
  import myhttp, {
    isEmpty,
    msgError,
    msgSuccess,
    msgWarning
  } from "../../utils/myhttp";
  import qs from "qs";
  import api from "../../utils/api";

  export default {
    data() {
      return {
        loading: "",
        active_crumb: "active_crumb", //面包屑当前颜色
        tableHeaderStyle: {
          //表头样式
          "background-color": "rgb(242,242,242)"
        },
        multipleSelection: [], //多选
        theRow: {}, //当前行数据
        theIndex: 0, //当前下标
        multiIDS: [], //多选
        theAdd: {
          // editSS:[]
        }, //新增数据
        editSS: [],
        isAdd: false, //是否新增
        isDelete: false, //是否删除
        hasMultiDelete: false, //是否多选
        searchForm: {
          searchText: "", //搜索字段
          post: '',
        },
        myTotal: 1, //分页总条数，默认1
        currentPage: 1, //初始化当前页
        nowPage: 1, //当前页
        thePageSize: 15, //每页条数
        addOrEdit: "新增用户", //新增或编辑标题
        tableData: [],
        tableProp: [

          {label: "账号", prop: "phoneNumber"},
          {label: "姓名", prop: "userName"},
          {label: "岗位", prop: "post"},
          {label: "性别", prop: "gender"},
          {label: "创建时间", prop: "createTime", sort: true, width: 155},
          {
            label: "状态", prop: "userState", html(prop) {
              return prop === 1 ? '<span style=color:green>启用</span>' : '<span style=color:red>禁用</span>';
            }
          },
          {
            label: "部门", prop: "department", html(prop) {
              // return prop === '1' ? '监理公司' : '监理公司';
              if (prop === '1' || prop === '监理公司') {
                return '<span>监理公司</span>'
              }
            }
          },
          {
            label: "专业", prop: "userMajorInfoList", html(prop) {
              // return Return(prop,(a,v)=>a+'、'+v.majorName.replace('专业',''),'').slice(1);
              return Return(prop, (a, v) => a + '、' + (v.majorName || '')).slice(1);
            }
          },
          {label: "创建人", prop: "createPerson"},
        ],

        rules: {
          //表单验证
          phoneNumber: [
            {required: true, message: "请输入账号", trigger: "blur"},
            {min: 1, max: 11, message: "长度在 1 到 11 个字符", trigger: "blur"}
          ],
          userName: [
            {required: true, message: "请输入用户名", trigger: "blur"}
          ],
          post: [
            {required: true, message: "请选择岗位", trigger: "change"}
          ],
          gender: [
            {required: true, message: "请选择性别", trigger: "change"}
          ],
          // department: [
          //   { required: true, message: "请选择部门", trigger: "change" }
          // ],
          // major: [
          //   { required: true, message: "请选择专业", trigger: "blur" }
          // ]
        },
        allPost: [
          {value: "工程师", label: "工程师"},
          {value: "公司、部门领导", label: "部门领导"},
          {value: "系统管理员", label: "系统管理员"}
        ],
        allDepartment: [
          {value: "1", label: "监理公司"}
        ],
        allGender: [
          {value: "男", label: "男"},
          {value: "女", label: "女"}
        ],
        theEdit: {},
        isEdit: false,
        allMajor: [],
        // options:[
        //   { value: "1",label: "系统管理员" },
        //   { value: "2",label: "项目运营员" }
        // ],
        // role:"",
        // roleAll:"",
        // optionsAll:[
        //   { value: "ALL", label: "全选" },
        //   { value: "1", label: "轮播图管理" },
        //   { value: "2", label: "项目管理" },
        //   { value: "3", label: "用户管理" },
        //   { value: "4", label: "权限管理" },
        //   { value: "5", label: "日志管理" },
        // ],
        specialty: '',
        showBack: false,
      };
    },
    watch: {
      // isAdd(val){
      //   alert(val)
      //   if(!val){
      //     this.theAdd.phoneNumber = "";
      //     this.theAdd.userName = "";
      //     this.theAdd.post = "";
      //     this.theAdd.department = "";
      //     this.theAdd.gender = "";
      //     this.theAdd.major = "";
      //   }
      // }
    },
    components: {},
    methods: {
      resetForm() {
        this.$refs.searchForm.resetFields();
        this.getAllList();
        this.showBack = false;
      },
      //===========================全选===================================
      // selectAll(val) {
      //   let allValues = [];
      //   for (let item of this.optionsAll) {
      //     allValues.push(item.value)
      //   };
      //   const oldVal = this.oldOptions.length === 1 ? this.oldOptions[0] : [];
      //   if (val.includes('ALL')) this.roleAll = allValues;
      //   if (oldVal.includes('ALL') && !val.includes('ALL')) this.roleAll = [];
      //   if (oldVal.includes('ALL') && val.includes('ALL')) {
      //     const switch = val.indexOf('ALL');
      //     val.splice(switch, 1);
      //     this.roleAll = val;
      //   };
      //   if (!oldVal.includes('ALL') && !val.includes('ALL')) {
      //     console.log(11)
      //     if (val.length === allValues.length - 1) this.roleAll = ['ALL'].concat(val);
      //   }
      //   //储存当前最后的结果 作为下次的老数据
      //   this.oldOptions[0] = this.roleAll;
      // },
      //批量导入
      // upload: async function() {
      //   this.planid = row.planId;
      //   this.Plantype = row.plantype;
      // },
      uploadFileMethod: async function (param) {
        var testmsg = param.file.name.substring(
          param.file.name.lastIndexOf(".") + 1
        );
        if (testmsg === "xls" || testmsg === "xlsx") {
          let fileName = param.file.name;
          let xlsname = fileName.substring(0, fileName.lastIndexOf("."));
          let fileObject = param.file;
          let formData = new FormData();
          formData.append("file", fileObject);
          formData.append("createPerson", localStorage.getItem('loginName'));
          // return console.warn(formData,param); baseUrl_online
          $.file($.api.baseUrl_online + api.importExcel, formData, (res, err) => {
            if (res.result !== 'success' || err) return $.msgError(res.msg || 'error!');
            // else return $.msgSuccess(res.msg||'导入成功!');
            this.getAllList();
          });
        } else {
          this.$message.error("上传文件只能是 xls/xlsx 格式!");
          return false;
        }
        ;
      },
      //编辑权限
      editLimit(index, row) {
        this.$router.push({
          name: "limitEdit",
          params: {
            user_id: row.userId,
            user_name: row.userName,
            user_account: row.phoneNumber,
            state: row.userState,
            role_id: row.roleId,
            menu_d: row.userMenuInfoList || [],
          }
        });
      },
      doJinYong: async function (index, row) {
        var res = await $.post('updateUserState', {
          userId: row.userId,
          userState: 2,
        });
        if (!res.success) return $.msgError(res.msg || 'error!');
        this.getAllList();
      },
      doQiYong: async function (index, row) {
        var res = await $.post('updateUserState', {
          userId: row.userId,
          userState: 1,
        });
        if (!res.success) return $.msgError(res.msg || 'error!');
        this.getAllList();
      },
      doAdd(formName) {
        //删除或新增
        this.$refs[formName].validate(valid => {
          if (valid) {
            if (this.addOrEdit == "新增用户") {
              this.addFunction(); //新增
              // this.$refs['ruleForm'].resetFields();
            }
          } else {
            msgWarning(this, "请填写必要信息！");
            return false;
          }
        });
      },
      closeDialog() {
        this.$nextTick(() => {
          this.isAdd = false;
          this.$refs["ruleForm"].resetFields();
        });
      },
      //新增取消
      addFalse() {
        this.isAdd = false;
        this.$refs['ruleForm'].resetFields();
      },
      addFunction: async function () {
        if (!G.isPhone(this.theAdd.phoneNumber)) {
          return $.msgError("请输入正确的手机号！");
        }
        ;
        const allMajor = this.allMid;
        var res = await $.post('addUser', {
          createPerson: localStorage.getItem('loginName'),
          phoneNumber: this.theAdd.phoneNumber,//电话号码
          userName: this.theAdd.userName,//用户名
          post: this.theAdd.post,//岗位
          gender: this.theAdd.gender,//性别
          userState: 1,//状态
          department: this.theAdd.department,//部门
          UserMajorList: this.theAdd.major.map((v, i) => ({majorId: v, majorName: allMajor[v].majorName})),
          // UserMajorList:JSON.stringify(this.theAdd.majorId)
        });
        if (!res.success) return $.msgError(res.msg || 'error!');
        this.isAdd = false;
        this.getAllList();
        this.$refs['ruleForm'].resetFields();
      },
      editFunction: async function () {
        const allMajor = this.allMid;
        var res = await $.post('updateUser', {
          userId: this.theEdit.userId,// 用户id
          phoneNumber: this.theEdit.phoneNumber,//电话号码
          userName: this.theEdit.userName,//用户名
          post: this.theEdit.post,//岗位
          roleId: this.theEdit.roleId,//岗位
          gender: this.theEdit.gender,//性别
          department: this.theEdit.department,//部门
          UserMajorList: this.editSS.map((v, i) => ({majorId: v, majorName: allMajor[v].majorName})),
        });
        if (!res.success) return $.msgError(res.msg || 'error!');
        this.isEdit = false;
        this.getAllList();
      },
      toAdd() {
        //调起新增弹窗
        this.addOrEdit = "新增用户";
        this.isAdd = true;
        // this.theAdd = {};
        // this.getAllmajor();
      },
      handleEdit(index, row) {
        //调起编辑弹窗
        this.theEdit = row;
        this.addOrEdit = "编辑用户";
        this.isEdit = true;
        const A = [];
        // A.length = 0;
        row.editSS = mapArr(row.userMajorInfoList || [], v => {
          if (v.majorId) {
            A.push(v.majorId);
            return v.majorId + '';
          }
          ;
        });
        this.editSS = A;
      },
      doSearch() {
        //搜索方法
        this.getAllList();
        this.showBack = true;
      },
      openLoading() {
        //loading请求等待
        this.loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
      },
      getAllList: async function (pageNum, pageSize) {
        var res = await $.post('getAllUser', {
          pageNum, //当前页
          pageSize,//每页显示条数
          searchText: this.searchForm.searchText,//搜索文本
          post: this.searchForm.post,
        });
        // console.log(arguments);
        $return('__', res);
      },
      //专业
      getAllmajor: async function () {
        var res = await $.post('getAllMajor', {
          parentId: 0,
        });
        if (!res.success) return;
        const allMid = this.allMid;
        this.allMajor = res.items.map(v => {
          v.label = v.majorName;
          allMid[v.value = v.majorId + ''] = v;
          return v;
        });
        const S = this.theAdd.editSS;
        S && this.$nextTick(() => {
          this.editSS = S;
        })
      },
    },
    created() {
      this.allMid = {__proto__: null};
      this.getAllmajor();
      // this.getAllList();
      // console.log(this.Height,this);
    },
    mounted() {
    }
  };
</script>
<style scoped>
  .active_crumb {
    color: rgb(90, 160, 230);
  }
</style>


